package com.cbgolf.oa.views;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Matrix;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.cbgolf.oa.R;
import com.cbgolf.oa.adapter.MyBaseAdapter;
import com.cbgolf.oa.adapter.MyFragmentPagerAdapter;
import com.cbgolf.oa.base.BaseView;
import com.cbgolf.oa.contract.IOrderContract.IOrderView;
import com.cbgolf.oa.contract.IOrderContract.IOrderWaiter;
import com.cbgolf.oa.fragment.OrderFragment;
import com.cbgolf.oa.manager.OrderManager;
import com.cbgolf.oa.util.DensityUtil;
import com.cbgolf.oa.util.ScreenUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.util.ViewUtils;
import com.cbgolf.oa.widget.autolayout.utils.AutoUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author lq
 * @date 2018/4/11
 */

public class OrderViewImp extends BaseView implements IOrderView {

  /**
   * top
   */
  @BindView(R.id.topBack_ll)
  View topBack;
  @BindView(R.id.title_tv)
  TextView titleTv;
  @BindView(R.id.ll_topright_filter)
  View topRightVi;
  @BindView(R.id.tv_topright_filter)
  TextView topRightTv;
  @BindView(R.id.iv_topright_filter)
  ImageView topRightIv;
  /**
   * 全部
   */
  @BindView(R.id.a_order_all_ll)
  View allVi;
  @BindView(R.id.a_order_all_tv)
  TextView allTv;
  /**
   * 待确认
   */
  @BindView(R.id.a_order_waitpay_ll)
  View waitConfirmVi;
  @BindView(R.id.a_order_waitpay_tv)
  TextView waitConfirmTv;
  /**
   * 待验证
   */
  @BindView(R.id.a_order_haspay_ll)
  View waitVerifyVi;
  @BindView(R.id.a_order_haspay_tv)
  TextView waitVerifyTv;
  /**
   * 已完成
   */
  @BindView(R.id.a_order_hascancel_ll)
  View overedVi;
  @BindView(R.id.a_order_hascancel_tv)
  TextView overedTv;
  /**
   * 已取消
   */
  @BindView(R.id.a_order_has_tunding_ll)
  View canceledVi;
  @BindView(R.id.a_order_has_tunding_tv)
  TextView canceledTv;

  @BindView(R.id.a_order_line_ll)
  View lineView;
  @BindView(R.id.a_order_line_iv)
  ImageView lineIv;

  /**
   * all pager
   */
  @BindView(R.id.a_order_all_viewpager)
  ViewPager viewPagerAll;
  /**
   * teetime pager
   */
  @BindView(R.id.a_order_dingchang_viewpager)
  ViewPager viewPagerTeetime;
  /**
   * match pager
   */
  @BindView(R.id.a_order_match_viewpager)
  ViewPager viewPagerMatch;
  /**
   * match pager
   */
  @BindView(R.id.viewpager_order_group)
  ViewPager viewPagerGroup;
  /**
   * match pager
   */
  @BindView(R.id.viewpager_order_hotel)
  ViewPager viewPagerHotel;
  /**
   * match pager
   */
  @BindView(R.id.viewpager_order_combo)
  ViewPager viewPagerCombo;
  /**
   * 当前选中位置
   */
  private int currentIndex = 0;
  /**
   * indicator 偏移距离
   */
  private int offSet = 0;
  /**
   * all  fragment list
   */
  private List<Fragment> listAll = new ArrayList<>();
  /**
   * match  fragment list
   */
  private List<Fragment> listMatch = new ArrayList<>();
  /**
   * teetime fragment list
   */
  private List<Fragment> listBook = new ArrayList<>();
  /**
   * teetime fragment list
   */
  private List<Fragment> listGroup = new ArrayList<>();
  /**
   * teetime fragment list
   */
  private List<Fragment> listHotel = new ArrayList<>();
  /**
   * teetime fragment list
   */
  private List<Fragment> listCombo = new ArrayList<>();

  /**
   * worker
   */
  private IOrderWaiter worker;
  /**
   * types
   */
  private String[] orderTypes = new String[]{
      "全部", "订场", "比赛", "团队", "酒店", "住打"
  };
  //
  private int orderType;
  /**
   * list fragment index
   */
  private final int ONE = 0;
  private final int TWO = 1;
  private final int THREE = 2;
  private final int FOUR = 3;
  private final int FIVE = 4;

  public OrderViewImp(Activity act, IOrderWaiter waiter) {
    ButterKnife.bind(this, act);
    this.worker = waiter;
    super.init(act);
  }

  @Override
  protected void setViews() {
    ViewUtils.setText(titleTv, worker.getActivityTitle());
    ViewUtils.setVisible(topRightVi, true);
    ViewUtils.setVisible(topRightTv, true);
    ViewUtils.setText(topRightTv, "全部");
    ViewUtils.setImage(topRightIv, R.mipmap.shaixuan);
    initLine();
    initViewPagers();
  }

  private void initLine() {
    offSet = ScreenUtil.getWidth() / 5;
    Matrix matrix = new Matrix();
    matrix.postTranslate(offSet, 0);
    lineIv.setImageMatrix(matrix);
    int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    waitConfirmTv.measure(w, w);
    int width = waitConfirmTv.getMeasuredWidth();
    ViewGroup.LayoutParams vl = lineIv.getLayoutParams();
    vl.width = width;
    lineIv.setLayoutParams(vl);
    int padding = (offSet - width) / 2;
    lineView.setPadding(padding, 0, padding, 0);
  }

  private void initViewPagers() {
    initAllPager();
    initBookPager();
    initMatchPager();
    initGroupPager();
    initHotelPager();
    initComboPager();
  }

  private void initComboPager() {
    listCombo.clear();
    listCombo.add(ONE, OrderFragment.newInstance(OrderManager.ORDER_STATE_ALL,
        OrderManager.ORDER_TYPE_LIVE_PLAY_REQUEST));
    listCombo.add(TWO, OrderFragment.newInstance(String.valueOf(OrderManager.ORDER_STATE_PAY_HAS),
        OrderManager.ORDER_TYPE_LIVE_PLAY_REQUEST));
    listCombo
        .add(THREE, OrderFragment.newInstance(String.valueOf(OrderManager.ORDER_STATE_CONFIRMED),
            OrderManager.ORDER_TYPE_LIVE_PLAY_REQUEST));
    listCombo.add(FOUR, OrderFragment.newInstance(String.valueOf(OrderManager.ORDER_STATE_OVERD),
        OrderManager.ORDER_TYPE_LIVE_PLAY_REQUEST));
    listCombo.add(FIVE, OrderFragment.newInstance(String.valueOf(OrderManager.ORDER_STATE_CANCELED),
        OrderManager.ORDER_TYPE_LIVE_PLAY_REQUEST));
    viewPagerMatch.setOffscreenPageLimit(1);
    FragmentPagerAdapter matchPagerAdapter = new MyFragmentPagerAdapter(
        ((FragmentActivity) context).getSupportFragmentManager(), listCombo);
    viewPagerCombo.setAdapter(matchPagerAdapter);
    viewPagerCombo.setCurrentItem(0);
  }

  private void initHotelPager() {
    listHotel.clear();
    listHotel.add(ONE, OrderFragment.newInstance(OrderManager.ORDER_STATE_ALL,
        OrderManager.ORDER_TYPE_HOTEL_REQUEST));
    listHotel.add(TWO, OrderFragment.newInstance(String.valueOf(OrderManager.ORDER_STATE_PAY_HAS),
        OrderManager.ORDER_TYPE_HOTEL_REQUEST));
    listHotel
        .add(THREE, OrderFragment.newInstance(String.valueOf(OrderManager.ORDER_STATE_CONFIRMED),
            OrderManager.ORDER_TYPE_HOTEL_REQUEST));
    listHotel.add(FOUR, OrderFragment.newInstance(String.valueOf(OrderManager.ORDER_STATE_OVERD),
        OrderManager.ORDER_TYPE_HOTEL_REQUEST));
    listHotel.add(FIVE, OrderFragment.newInstance(String.valueOf(OrderManager.ORDER_STATE_CANCELED),
        OrderManager.ORDER_TYPE_HOTEL_REQUEST));
    viewPagerMatch.setOffscreenPageLimit(1);
    FragmentPagerAdapter matchPagerAdapter = new MyFragmentPagerAdapter(
        ((FragmentActivity) context).getSupportFragmentManager(), listHotel);
    viewPagerHotel.setAdapter(matchPagerAdapter);
    viewPagerHotel.setCurrentItem(0);
  }

  private void initGroupPager() {
    listGroup.clear();
    listGroup.add(ONE, OrderFragment.newInstance(OrderManager.ORDER_STATE_ALL,
        OrderManager.ORDER_TYPE_GROUP_REQUEST));
    listGroup.add(TWO, OrderFragment.newInstance(String.valueOf(OrderManager.ORDER_STATE_PAY_HAS),
        OrderManager.ORDER_TYPE_GROUP_REQUEST));
    listGroup
        .add(THREE, OrderFragment.newInstance(String.valueOf(OrderManager.ORDER_STATE_CONFIRMED),
            OrderManager.ORDER_TYPE_GROUP_REQUEST));
    listGroup.add(FOUR, OrderFragment.newInstance(String.valueOf(OrderManager.ORDER_STATE_OVERD),
        OrderManager.ORDER_TYPE_GROUP_REQUEST));
    listGroup.add(FIVE, OrderFragment.newInstance(String.valueOf(OrderManager.ORDER_STATE_CANCELED),
        OrderManager.ORDER_TYPE_GROUP_REQUEST));
    viewPagerMatch.setOffscreenPageLimit(1);
    FragmentPagerAdapter matchPagerAdapter = new MyFragmentPagerAdapter(
        ((FragmentActivity) context).getSupportFragmentManager(), listGroup);
    viewPagerGroup.setAdapter(matchPagerAdapter);
    viewPagerGroup.setCurrentItem(0);
  }


  private void initBookPager() {
    listBook.clear();
    listBook.add(ONE, OrderFragment.newInstance("", OrderManager.ORDER_TYPE_TEETIME_REQUEST));
    listBook.add(TWO,
        OrderFragment.newInstance(String.valueOf(OrderManager.ORDER_STATE_PAY_HAS),
            OrderManager.ORDER_TYPE_TEETIME_REQUEST));
    listBook.add(THREE,
        OrderFragment.newInstance(String.valueOf(OrderManager.ORDER_STATE_CONFIRMED),
            OrderManager.ORDER_TYPE_TEETIME_REQUEST));
    listBook.add(FOUR, OrderFragment.newInstance(String.valueOf(OrderManager.ORDER_STATE_OVERD),
        OrderManager.ORDER_TYPE_TEETIME_REQUEST));
    listBook.add(FIVE, OrderFragment.newInstance(String.valueOf(OrderManager.ORDER_STATE_CANCELED),
        OrderManager.ORDER_TYPE_TEETIME_REQUEST));
    viewPagerTeetime.setOffscreenPageLimit(1);
    FragmentPagerAdapter bookPagerAdapter = new MyFragmentPagerAdapter(
        ((FragmentActivity) context).getSupportFragmentManager(), listBook);
    viewPagerTeetime.setAdapter(bookPagerAdapter);
    viewPagerTeetime.setCurrentItem(0);
  }


  private void initMatchPager() {
    listMatch.clear();
    listMatch.add(ONE, OrderFragment.newInstance(OrderManager.ORDER_STATE_ALL,
        OrderManager.ORDER_TYPE_MATCH_REQUEST));
    listMatch.add(TWO, OrderFragment.newInstance(String.valueOf(OrderManager.ORDER_STATE_PAY_HAS),
        OrderManager.ORDER_TYPE_MATCH_REQUEST));
    listMatch
        .add(THREE, OrderFragment.newInstance(String.valueOf(OrderManager.ORDER_STATE_CONFIRMED),
            OrderManager.ORDER_TYPE_MATCH_REQUEST));
    listMatch.add(FOUR, OrderFragment.newInstance(String.valueOf(OrderManager.ORDER_STATE_OVERD),
        OrderManager.ORDER_TYPE_MATCH_REQUEST));
    listMatch.add(FIVE, OrderFragment.newInstance(String.valueOf(OrderManager.ORDER_STATE_CANCELED),
        OrderManager.ORDER_TYPE_MATCH_REQUEST));
    viewPagerMatch.setOffscreenPageLimit(1);
    FragmentPagerAdapter matchPagerAdapter = new MyFragmentPagerAdapter(
        ((FragmentActivity) context).getSupportFragmentManager(), listMatch);
    viewPagerMatch.setAdapter(matchPagerAdapter);
    viewPagerMatch.setCurrentItem(0);
  }


  private void initAllPager() {
    listAll.clear();
    listAll.add(ONE, OrderFragment.newInstance(OrderManager.ORDER_STATE_ALL,
        OrderManager.ORDER_TYPE_ALL_REQUEST));
    listAll.add(TWO, OrderFragment.newInstance(String.valueOf(OrderManager.ORDER_STATE_PAY_HAS),
        OrderManager.ORDER_TYPE_ALL_REQUEST));
    listAll
        .add(THREE, OrderFragment.newInstance(String.valueOf(OrderManager.ORDER_STATE_CONFIRMED),
            OrderManager.ORDER_TYPE_ALL_REQUEST));
    listAll.add(FOUR, OrderFragment.newInstance(String.valueOf(OrderManager.ORDER_STATE_OVERD),
        OrderManager.ORDER_TYPE_ALL_REQUEST));
    listAll.add(FIVE, OrderFragment.newInstance(String.valueOf(OrderManager.ORDER_STATE_CANCELED),
        OrderManager.ORDER_TYPE_ALL_REQUEST));
    viewPagerAll.setOffscreenPageLimit(1);
    FragmentPagerAdapter pagerAdapterAll = new MyFragmentPagerAdapter(
        ((FragmentActivity) context).getSupportFragmentManager(), listAll);
    viewPagerAll.setAdapter(pagerAdapterAll);
    viewPagerAll.setCurrentItem(0);

  }

  @Override
  protected void setListener() {
    ViewUtils.setClick(topBack, v -> worker.back());
    allVi.setOnClickListener(v -> checkPage(0));
    waitConfirmVi.setOnClickListener(v -> checkPage(1));
    waitVerifyVi.setOnClickListener(v -> checkPage(2));
    overedVi.setOnClickListener(v -> checkPage(3));
    canceledVi.setOnClickListener(v -> checkPage(4));
    setViewPageListener();
    ViewUtils.setClick(topRightVi, v -> showPop());
  }


  private void showPop() {
    PopupWindow pop = new PopupWindow();
    @SuppressLint("InflateParams") View view = ViewUtils
        .inflate(context, R.layout.pop_list_order);
    View layout = ButterKnife.findById(view, R.id.layout);
    ListView listView = ButterKnife.findById(view, R.id.listView);

    MyBaseAdapter<String> adapter = new MyBaseAdapter<String>(R.layout.item_tv_dp35, context,
        orderTypes) {
      @Override
      public View getView(int position, View convertView, ViewGroup parent, String s) {
        setText(R.id.tv, s);
        setOnClick(R.id.tv, v -> {
          pop.dismiss();
          ViewUtils.setText(topRightTv, s);
          orderType = position;
          showOrders(position);
        });
        return convertView;
      }
    };
    listView.setAdapter(adapter);
    ViewUtils
        .setLayoutParams(layout, (int) (ScreenUtil.getWidth() / 3.5), LayoutParams.WRAP_CONTENT);
    AutoUtil.autoSize(view);
    pop.setContentView(view);
    pop.setWidth(LayoutParams.WRAP_CONTENT);
    pop.setHeight(LayoutParams.WRAP_CONTENT);
    pop.setOutsideTouchable(true);
    pop.setFocusable(true);
    pop.setTouchable(true);
    pop.setBackgroundDrawable(new ColorDrawable(0xffffffff));
    pop.setOnDismissListener(() -> ScreenUtil.LightOn(context));
    pop.showAsDropDown(topRightVi, -DensityUtil.dip2px(context, 15), 0);
    ScreenUtil.LightOff(context);

  }

  private void setViewPageListener() {
    ViewPager[] pagers = new ViewPager[]{
        viewPagerTeetime, viewPagerAll, viewPagerMatch, viewPagerGroup, viewPagerHotel,
        viewPagerCombo
    };
    for (ViewPager pager : pagers) {
      pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        int width = offSet;

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
          Animation animation = new TranslateAnimation(currentIndex * width,
              position * width, 0, 0);
          currentIndex = position;
          animation.setFillAfter(true);
          animation.setDuration(150);
          lineIv.startAnimation(animation);
          checkPage(position);
          refreshOrder(position);

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
      });
    }
  }

  private void showOrders(int type) {
    ViewUtils.setVisible(viewPagerAll, type == OrderManager.ORDER_TYPE_ALL_INDEX);
    ViewUtils.setVisible(viewPagerMatch, type == OrderManager.ORDER_TYPE_MATCH_INDEX);
    ViewUtils.setVisible(viewPagerTeetime, type == OrderManager.ORDER_TYPE_TEETIME_INDEX);
    ViewUtils.setVisible(viewPagerHotel, type == OrderManager.ORDER_TYPE_HOTEL_INDEX);
    ViewUtils.setVisible(viewPagerGroup, type == OrderManager.ORDER_TYPE_GROUP_INDEX);
    ViewUtils.setVisible(viewPagerCombo, type == OrderManager.ORDER_TYPE_COMBO_INDEX);
    switch (type) {
      case OrderManager.ORDER_TYPE_TEETIME_INDEX:
        viewPagerTeetime.setCurrentItem(currentIndex, true);
        break;
      case OrderManager.ORDER_TYPE_ALL_INDEX:
        viewPagerAll.setCurrentItem(currentIndex, true);
        break;
      case OrderManager.ORDER_TYPE_MATCH_INDEX:
        viewPagerMatch.setCurrentItem(currentIndex, true);
        break;
      case OrderManager.ORDER_TYPE_GROUP_INDEX:
        viewPagerGroup.setCurrentItem(currentIndex, true);
        break;
      case OrderManager.ORDER_TYPE_HOTEL_INDEX:
        viewPagerHotel.setCurrentItem(currentIndex, true);
        break;
      case OrderManager.ORDER_TYPE_COMBO_INDEX:
        viewPagerCombo.setCurrentItem(currentIndex, true);
        break;
      default:
        break;
    }
  }

  private void checkPage(int index) {
    resetTextColor();
    switch (index) {
      case 0:
        allTv.setTextColor(ContextCompat.getColor(context, R.color.bg_blue));
        setCurrentPage(0);
        break;
      case 1:
        waitConfirmTv.setTextColor(ContextCompat.getColor(context, R.color.bg_blue));
        setCurrentPage(1);
        break;
      case 2:
        waitVerifyTv.setTextColor(ContextCompat.getColor(context, R.color.bg_blue));
        setCurrentPage(2);
        break;
      case 3:
        overedTv.setTextColor(ContextCompat.getColor(context, R.color.bg_blue));
        setCurrentPage(3);
        break;
      case 4:
        canceledTv.setTextColor(ContextCompat.getColor(context, R.color.bg_blue));
        setCurrentPage(4);
        break;
      default:
        break;
    }

  }

  private void setCurrentPage(int index) {
    switch (orderType) {
      case OrderManager.ORDER_TYPE_TEETIME_INDEX:
        viewPagerTeetime.setCurrentItem(index);
        break;
      case OrderManager.ORDER_TYPE_MATCH_INDEX:
        viewPagerMatch.setCurrentItem(index);
        break;
      case OrderManager.ORDER_TYPE_ALL_INDEX:
        viewPagerAll.setCurrentItem(index);
        break;
      case OrderManager.ORDER_TYPE_GROUP_INDEX:
        viewPagerGroup.setCurrentItem(index);
        break;
      case OrderManager.ORDER_TYPE_HOTEL_INDEX:
        viewPagerHotel.setCurrentItem(index);
        break;
      case OrderManager.ORDER_TYPE_COMBO_INDEX:
        viewPagerCombo.setCurrentItem(index);
        break;
      default:
        break;
    }
  }

  private void refreshOrder(int index) {
    switch (orderType) {
      case OrderManager.ORDER_TYPE_TEETIME_INDEX:
        refreshOrder(listBook, index);
        break;
      case OrderManager.ORDER_TYPE_MATCH_INDEX:
        refreshOrder(listMatch, index);
        break;
      case OrderManager.ORDER_TYPE_ALL_INDEX:
        refreshOrder(listAll, index);
        break;
      case OrderManager.ORDER_TYPE_GROUP_INDEX:
        refreshOrder(listGroup, index);
        break;
      case OrderManager.ORDER_TYPE_HOTEL_INDEX:
        refreshOrder(listHotel, index);
        break;
      case OrderManager.ORDER_TYPE_COMBO_INDEX:
        refreshOrder(listCombo, index);
        break;
      default:
        break;
    }
  }

  private void refreshOrder(List<Fragment> list, int index) {
    if (Util.listIsNull(list) || list.size() <= index) {
      return;
    }

    if (null != list.get(index) && list.get(index) instanceof OrderFragment) {
      ((OrderFragment) list.get(index)).refreshData();
    }
  }

  private void resetTextColor() {
    allTv.setTextColor(ContextCompat.getColor(context, R.color.text_hint));
    waitVerifyTv.setTextColor(ContextCompat.getColor(context, R.color.text_hint));
    waitConfirmTv.setTextColor(ContextCompat.getColor(context, R.color.text_hint));
    overedTv.setTextColor(ContextCompat.getColor(context, R.color.text_hint));
    canceledTv.setTextColor(ContextCompat.getColor(context, R.color.text_hint));
  }
}
